const api = require('../../../../ws_micro_shop/utils/api.js');
const utils = require('../../../../ws_micro_shop/utils/utils.js');
const tools = require('../../../../ws_micro_shop/utils/getuserinfo.js');
const app = getApp();
const { module: moduleName } = app.siteInfo;
const util = app.util;

let timer = null;
let p = 1;

Page({
  data: {
    id: null,
    goods: {},
    show_attr_picker: false,
    form: {
      number: 1,
    },
    idx: 1,
    level: 0,
    comment_list: [],
    comment_count: {
      score_all: 0,
      score_6: 0,
      score_3: 0,
      score_2: 0,
      score_1: 0,
    },
    autoplay: true,
    img_hide: true,
    hide: 'hide',
    x:wx.systemInfo.windowWidth,
    y:wx.systemInfo.windowHeight - 20,
    miaosha_end_time_over: {
      h: '--',
      m: '--',
      s: '--',
      type: 0,
    },
    attachment_url: app.siteInfo.attachment_url,
    theme: app.themeData,
    abnorData: {
      imgSrc: '/common/static/images/abnor-09.png',
      text: '暂无相关评价',
    },
    show_service: false,
    unit: '',
    imgUrl: app.imgUrl,
  },
  onLoad(op) {
    let options = op || {};
    app.v8_card_action_log = [];
    let parent_id = 0;
    let shop_id = 0;
    let share_scene = '';
    let user_id = options.user_id;
    let scene = decodeURIComponent(options.scene);
    this.setData({
      orgPrice: app.ws_micro_shop_globalData.orgPrice,
    });
    if (options && options.shopid) {
      app.ws_micro_shop_globalData.shopid = options.shopid;
      shop_id = options.shopid;
    }
    app.tabbarindex = options.tabbarindex ? options.tabbarindex - 0 : app.tabbarindex;
    app.pageOnLoad(this);
    app.bindGuide(op);
    let userinfo = wx.getStorageSync('user_info');
    let store = wx.getStorageSync('store');
    let that = this;
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    if (user_id) {
      parent_id = user_id;
      share_scene = 4;
    } else if (scene) {
      let { uid, gid, sid, g_id } = utils.scene_decode(scene);
      if (g_id && gid) {
        app.ws_micro_shop_globalData.last_share_guide_id = g_id;
        app.ws_micro_shop_globalData.last_share_good_id = gid;
        app.ws_micro_shop_globalData.shopid = sid;
        options.id = gid;
        options.guide_id = g_id;
        options.shopid = sid;
        shop_id = sid;
      }
      if (uid && gid) {
        parent_id = uid;
        options.id = gid;
        shop_id = sid;
        app.ws_micro_shop_globalData.shopid = sid;
      } else {
        parent_id = scene;
      }
      share_scene = 6;
    }
    parent_id && (app.ws_micro_shop_globalData.parent_id = parent_id);
    app.loadShopSetting().then(res => {
      that.setData(res);
    }).then(() => {
      that.getFloatIcon();
    });
    let sessionFormStr = {
      shop_id: app.ws_micro_shop_globalData.shopid,
    };
    let serviceMessageTitle = '';
    let serviceMessagePath = 'details?id=' + options.id;

    if (userinfo && store) {
      Number(userinfo.info) === 0 && tools.onGetInfo(this, userinfo.auth_mode);
      app.loginBindParent({
        parent_id,
        shop_id,
        share_scene,
      });
      app.bindCard(options.openid, options.share_scene);
      this.bindCard(options);
      Number(store.comment_switch) === 1 && this.getComments(options.id, 0, 1);
      this.setData({
        store,
      });
      util.prepareBindInfo(options, moduleName, that);
    } else {
      app.ws_micro_shoplogin().then(res => {
        userinfo = wx.getStorageSync('user_info');
        Number(userinfo.info) === 0 && tools.onGetInfo(that, userinfo.auth_mode);
        util.prepareBindInfo(options, moduleName, that);
        this.bindCard(options);
        app.getStoreData().then(res => {
          store = wx.getStorageSync('store');
          Number(store.comment_switch) === 1 && that.getComments(options.id, 0, 1);
          app.loginBindParent({
            parent_id,
            shop_id,
            share_scene,
          });
          that.setData({
            store,
          });
        });
      });
    }
    if (options.guide_id) {
      app.ws_micro_shop_globalData.last_share_guide_id = options.guide_id;
      app.ws_micro_shop_globalData.last_share_good_id = options.id;
    }
    this.setData({
      opts: options,
      parent_id,
      shop_id,
      share_scene,
      commodityStatus: options.status === 'true', // true 的时候不能买；
      sessionFormStr: JSON.stringify(sessionFormStr),
      serviceMessageTitle,
      serviceMessagePath,
      isSaas: app.ws_micro_shop_globalData.isSaas,
    });
  },
  onShow() {
    wx.setNavigationBarTitle({
      title: '秒杀详情',
    });
    this.initGetGoods();
  },
  bindCard(options) {
    app.bindCard(options.openid, options.share_scene);
    app.v8_card_action_log.push({ name: 'transmitGoods', data:{goodsID: options.id, type: 'ms'}, timestamp: new Date().getTime(), to_openid: options.openid });
    app.util.statRequest({
      aa: JSON.stringify(app.v8_card_action_log),
      is_module: 0
    });
  },
  initGetGoods() {
    let options = this.data.opts;
    if (options && options.gid) {
      this.setData({
        gid: options.gid,
      });
      this.getActivityId(options.gid);
    }
    if (options && options.id) {
      this.setData({
        id: options.id,
      });
      this.getGoods(options.id);
    }
  },
  getActivityId(id) {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.user.getactiveid,
      data: {
        id,
      },
      success: function (res) {
        if (res.code === 0) {
          let aid = res.data;
          that.setData({
            id: aid,
          });
          that.getGoods(aid);
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg || '',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                app.util.navigateTo('/ws_micro_shop/pages/index/index');
              }
            },
          });
        }
      },
    });
  },
  getGoods(id) {
    let that = this;
    wx.showLoading({
      title: '加载中',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.miaosha.details,
      data: {
        id,
      },
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          let resp = res.data;
          that.setData({
            id,
            goods: resp,
            attr_group_list: resp.attr_group_list,
            miaosha_data: resp.miaosha.miaosha_data,
            serviceMessageTitle: resp.name,
            show_goods_comment: resp.show_goods_comment,
          });
          if (that.data.goods.miaosha) {
            that.setMiaoshaTimeOver();
          }
          that.selectDefaultAttr();
        }
        if (res.code === 1) {
          wx.showModal({
            title: '提示',
            content: res.msg || '',
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                if (that.data.gid) {
                  wx.navigateBack();
                } else {
                  app.util.navigateTo('/ws_micro_shop/pages/index/index');
                }
              }
            },
          });
        }
        if (res.code === -3) {
          app.ws_micro_shoplogin().then(res => {
            let userinfo = wx.getStorageSync('user_info');
            Number(userinfo.info) === 0 && tools.onGetInfo(that, userinfo.auth_mode);
            util.prepareBindInfo(that.data.opts, moduleName, that);
            app.getStoreData().then(res => {
              let store = wx.getStorageSync('store');
              Number(store.comment_switch) === 1 && that.getComments(that.data.opts.id, 0, 1);
              that.setData({
                store,
              });
              app.loginBindParent({
                parent_id: that.data.parent_id,
                shop_id: that.data.shop_id,
                share_scene: that.data.share_scene,
              });
            });
            that.getGoods(that.data.id);
          });
        }
      },
    });
  },
  selectDefaultAttr() {
    if (!this.data.goods || Number(this.data.goods.use_attr) !== 0) {
      return;
    }
    for (let i in this.data.attr_group_list) {
      if ({}.hasOwnProperty.call(this.data.attr_group_list, i)) {
        for (let j in this.data.attr_group_list[i].attr_list) {
          if (Number(i) === 0 && Number(j) === 0) {
            this.data.attr_group_list[i].attr_list[j]['checked'] = true;
          }
        }
      }
    }
    this.setData({
      attr_group_list: this.data.attr_group_list,
    });
  },
  getComments(id, score, page) {
    let that = this;
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.miaosha.comment_list,
      method: 'GET',
      data: {
        goods_id: id,
        score,
        page,
      },
      success: function(res) {
        wx.hideLoading();
        let { list, comment_count, comment_list = [], showComment, good_per } = res.data;
        if (list.length > 0) {
          that.setData({
            comment_count,
            comment_list: comment_list.concat(list.splice(0, 1)),
            good_per,
          });
        }
      },
    });
  },
  onGoodsImageClick(e) {
    let urls = [];
    let index = e.currentTarget.dataset.index;
    let pic_list = this.data.goods.pic_list;
    for (let i in pic_list) {
      if ({}.hasOwnProperty.call(pic_list, i)) {
        urls.push(pic_list[i].pic_url);
      }
    }
    wx.previewImage({
      urls: urls,
      current: urls[index],
    });
  },
  numberSub() {
    let num = this.data.form.number;
    if (num <= 1) {
      return true;
    }
    num--;
    this.setData({
      form: {
        number: num,
      },
    });
  },
  numberAdd() {
    let num = this.data.form.number;
    let buy_max = this.data.goods.miaosha.buy_max;
    num++;
    if (num > buy_max && Number(buy_max) !== 0) {
      wx.showToast({
        title: '一单限购' + buy_max + '件',
        icon: 'none',
      });
      return true;
    }
    this.setData({
      form: {
        number: num,
      },
    });
  },
  numberBlur(e) {
    let num = e.detail.value;
    let buy_max = this.data.goods.miaosha.buy_max;
    num = parseInt(num, 10);
    (isNaN(num) || num <= 0) && (num = 1);
    if (num > buy_max && Number(buy_max) !== 0) {
      wx.showToast({
        title: '一单限购' + buy_max + '件',
        icon: 'none',
      });
      num = buy_max;
    }
    this.setData({
      form: {
        number: num,
      },
    });
  },
  addCart() {
    this.submit('ADD_CART');
  },
  buyNow() {
    if (!this.data.goods.miaosha) {
      wx.showModal({
        title: '提示',
        content: '秒杀商品当前时间暂无活动',
        showCancel: false,
      });
      return;
    }
    this.submit('BUY_NOW');
  },
  submit(type) {
    let that = this;
    let { id, commodityStatus, show_attr_picker, miaosha_data = {}, form, goods, attr_group_list } = that.data;
    if (commodityStatus) {
      return wx.showToast({
        title: '秒杀尚未开始',
        icon: 'none',
      });
    }
    if (!show_attr_picker) {
      that.setData({
        show_attr_picker: true,
      });
      return true;
    }
    if (form.number > miaosha_data.rest_num) {
      wx.showToast({
        title: '商品库存不足，请选择其它规格或数量',
        icon: 'none',
      });
      return true;
    }

    if (form.number > goods.num) {
      wx.showToast({
        title: '商品库存不足，请选择其它规格或数量',
        icon: 'none',
      });
      return true;
    }
    
    let checked_attr_list = [];
    for (let i in attr_group_list) {
      if ({}.hasOwnProperty.call(attr_group_list, i)) {
        let attr = false;
        let attr_group_list_one = attr_group_list[i];
        for (let j in attr_group_list_one.attr_list) {
          if (attr_group_list_one.attr_list[j].checked) {
            attr = {
              attr_id: attr_group_list_one.attr_list[j].attr_id,
              attr_name: attr_group_list_one.attr_list[j].attr_name,
            };
            break;
          }
        }
        if (!attr) {
          wx.showToast({
            title: '请选择' + attr_group_list_one.attr_group_name,
            icon: 'none',
          });
          return true;
        } else {
          checked_attr_list.push({
            attr_group_id: attr_group_list_one.attr_group_id,
            attr_group_name: attr_group_list_one.attr_group_name,
            attr_id: attr.attr_id,
            attr_name: attr.attr_name,
          });
        }
      }
    }
    if (type === 'ADD_CART') {
      wx.showLoading({
        title: '正在提交',
        mask: true,
      });
      app.ws_micro_shoprequest({
        url: api.cart.add_cart,
        method: 'POST',
        data: {
          goods_id: id,
          attr: JSON.stringify(checked_attr_list),
          num: form.number,
        },
        success: function(res) {
          wx.hideLoading();
          wx.showToast({
            title: res.msg || '',
            duration: 1500,
          });
          that.setData({
            show_attr_picker: false,
          });
        },
      });
    }
    if (type === 'BUY_NOW') {
      that.setData({
        show_attr_picker: false,
      });
      wx.navigateTo({
        url: '/ws_micro_shop_ms/pages/miaosha/order-submit/order-submit?goods_info=' + JSON.stringify({
          goods_id: id,
          attr: checked_attr_list,
          num: form.number,
          custom_time: goods.miaosha.custom_time,
        }),
      });
    }
  },
  hideAttrPicker() {
    this.setData({
      show_attr_picker: false,
    });
  },
  disabledClick() {
    // it`s necessnary
  },
  showAttrPicker() {
    this.setData({
      show_attr_picker: true,
    });
  },
  attrClick(e) {
    let that = this;
    let attr_group_id = Number(e.currentTarget.dataset.groupId);
    let attr_id = Number(e.currentTarget.dataset.id);
    let attr_group_list = that.data.attr_group_list;
    for (let i in attr_group_list) {
      if (Number(attr_group_list[i].attr_group_id) !== attr_group_id) {
        continue;
      }
      for (let j in attr_group_list[i].attr_list) {
        if (Number(attr_group_list[i].attr_list[j].attr_id) === attr_id) {
          attr_group_list[i].attr_list[j].checked = true;
        } else {
          attr_group_list[i].attr_list[j].checked = false;
        }
      }
    }
    that.setData({
      attr_group_list,
    });
    let check_attr_list = [];
    let check_all = true;
    for (let i in attr_group_list) {
      if ({}.hasOwnProperty.call(attr_group_list, i)) {
        let group_checked = false;
        for (let j in attr_group_list[i].attr_list) {
          if (attr_group_list[i].attr_list[j].checked) {
            check_attr_list.push(attr_group_list[i].attr_list[j].attr_id);
            group_checked = true;
            break;
          }
        }
        if (!group_checked) {
          check_all = false;
          break;
        }
      }
    }
    if (!check_all) {
      return;
    }
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.default.goods_attr_info,
      data: {
        goods_id: that.data.id,
        attr_list: JSON.stringify(check_attr_list),
        type: 'ms',
      },
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          let goods = that.data.goods;
          let { price, num, pic, miaosha } = res.data;
          goods.price = price;
          goods.num = num;
          goods.attr_pic = pic;
          goods.oriprice = res.data.oriprice ? res.data.oriprice : 0;
          that.setData({
            goods,
            miaosha_data: miaosha,
          });
        }
      },
    });
  },
  favoriteAdd() {
    let that = this;
    let goods = that.data.goods;
    app.ws_micro_shoprequest({
      url: api.user.favorite_add,
      method: 'POST',
      data: {
        goods_id: goods.id,
      },
      success: function(res) {
        if (res.code === 0) {
          goods.is_favorite = 1;
          that.setData({
            goods,
          });
        }
      },
    });
  },
  favoriteRemove() {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.user.favorite_remove,
      method: 'post',
      data: {
        goods_id: that.data.goods.id,
      },
      success: function(res) {
        if (res.code === 0) {
          let goods = that.data.goods;
          goods.is_favorite = 0;
          that.setData({
            goods,
          });
        }
      },
    });
  },
  commentPicView(e) {
    let { index, pic_index } = e.currentTarget.dataset;
    let comments = this.data.comment_list[index].pic_list;
    wx.previewImage({
      current: comments[pic_index],
      urls: comments,
    });
  },
  onReachBottom() {
  },
  onShareAppMessage() {
    let that = this;
    let user_info = wx.getStorageSync('user_info');
    let { commodityStatus = false, id, goods } = that.data;
    let path = '/ws_micro_shop_ms/pages/miaosha/details/details?id=' + id + '&user_id=' + user_info.id + '&tabbarindex=' + app.tabbarindex + '&shopid=' + app.ws_micro_shop_globalData.shopid + '&status=' + commodityStatus;
    path = util.spliceSharePath(path, '4', moduleName);
    let shareShowPrice = wx.getStorageSync('store') && wx.getStorageSync('store').share_show_price;
    app.shareSendCoupon(that);
    let res = {
      path,
      title: `${Number(shareShowPrice) === 1 ? (that.data.goods.miaosha && that.data.goods.miaosha.miaosha_price ? that.data.goods.miaosha.miaosha_price : that.data.goods.price) + '元' : ''}${that.data.goods.name}`,            
      imageUrl: goods.pic_list[0].pic_url,
    };
    return res;
  },
  onShareTimeline() {
    let that = this;
    let user_info = wx.getStorageSync('user_info');
    let { commodityStatus = false, id, goods } = that.data;
    let shareShowPrice = wx.getStorageSync('store') && wx.getStorageSync('store').share_show_price;
    app.shareSendCoupon(that);
    return {
      title: `${Number(shareShowPrice) === 1 ? (that.data.goods.miaosha && that.data.goods.miaosha.miaosha_price ? that.data.goods.miaosha.miaosha_price : that.data.goods.price) + '元' : ''}${that.data.goods.name}`,
      imageUrl: goods.pic_list[0].pic_url,
      query: 'id=' + id + '&user_id=' + user_info.id + '&tabbarindex=' + app.tabbarindex + '&shopid=' + app.ws_micro_shop_globalData.shopid + '&status=' + commodityStatus
    }
  },
  onHide() {
    timer && clearInterval(timer);
    util.sendBindInfo(this.data);
  },
  onUnload() {
    timer && clearInterval(timer);
    util.sendBindInfo(this.data);
  },
  play(e) {
    let url = e.currentTarget.dataset.url;
    this.setData({
      url: url,
      hide: '',
      autoplay: false,
    });
    let videoContext = wx.createVideoContext('video');
    videoContext.play();
  },
  close(e) {
    if (e.currentTarget.id === 'video') {
      return true;
    }
    this.setData({
      hide: 'hide',
      autoplay: true,
    });
    let videoContext = wx.createVideoContext('video');
    videoContext.pause();
  },
  hide(e) {
    this.setData({
      img_hide: Number(e.detail.current) === 0,
    });
  },
  showShareModal() {
    this.setData({
      share_modal_active: 'active',
      no_scroll: true,
    });
  },
  shareModalClose() {
    this.setData({
      share_modal_active: '',
      no_scroll: false,
    });
  },
  getGoodsQrcode() {
    let that = this;
    that.setData({
      goods_qrcode_active: 'active',
      share_modal_active: '',
    });
    if (that.data.goods_qrcode) {
      return true;
    }
    app.ws_micro_shoprequest({
      url: api.miaosha.goods_qrcode,
      data: {
        goods_id: that.data.id,
      },
      success: function(res) {
        if (res.code === 0) {
          that.setData({
            goods_qrcode: res.data.pic_url,
          });
        }
        if (res.code === 1) {
          that.goodsQrcodeClose();
          wx.showModal({
            title: '提示',
            content: res.msg || '',
            showCancel: false,
          });
        }
      },
    });
  },
  goodsQrcodeClose() {
    this.setData({
      goods_qrcode_active: '',
      no_scroll: false,
    });
  },
  saveGoodsQrcode() {
    let that = this;
    if (!wx.saveImageToPhotosAlbum) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        showCancel: false,
      });
      return;
    }
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.writePhotosAlbum'] === 'undefined') {
          that.downLoadGoodsImg();
        } else if (res.authSetting['scope.writePhotosAlbum'] === false) {
          that.setData({
            open_setting: true,
          });
        } else {
          that.downLoadGoodsImg();
        }
      },
    });
  },
  downLoadGoodsImg() {
    let _this = this;
    wx.showLoading({
      title: '正在下载图片',
      mask: true,
    });
    wx.downloadFile({
      url: _this.data.goods_qrcode,
      success: function(e) {
        wx.showLoading({
          title: '正在保存图片',
          mask: true,
        });
        wx.saveImageToPhotosAlbum({
          filePath: e.tempFilePath,
          success: function() {
            wx.showModal({
              title: '提示',
              content: '商品海报保存成功',
              showCancel: false,
            });
          },
          fail: function(e) {
            wx.showModal({
              title: '提示',
              content: '图片保存失败',
              showCancel: false,
            });
          },
          complete: function(e) {
            wx.hideLoading();
          },
        });
      },
      fail: function(e) {
        wx.showModal({
          title: '图片下载失败',
          content: e.errMsg + ';' + _this.data.goods_qrcode,
          showCancel: false,
        });
      },
      complete: function(e) {
        wx.hideLoading();
      },
    });
  },
  goodsQrcodeClick(e) {
    let src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src],
    });
  },
  closeCouponBox() {
    this.setData({
      get_coupon_list: '',
    });
  },
  setMiaoshaTimeOver() {
    let that = this;
    function _init() {
      // 兼容自定义时间段 
      let { miaosha } = that.data.goods;
      let bgTime = miaosha.begin_time;
      let endTime = miaosha.end_time;
      let nowTime = miaosha.now_time;
      let time_over = 0;
      let type = 0; // 0 距离活动结束还剩  1距离活动开始还剩
      
      if (nowTime >= bgTime && nowTime <= endTime) {
        // 进行中
        time_over = endTime - nowTime;
        type = 0;
      }
      if (nowTime <= bgTime) {
        // 即将开始
        time_over = bgTime - nowTime;
        type = 1;
      }
      if (nowTime > endTime) {
        // 已结束
        type = 2;
      }
      that.data.goods.miaosha.now_time++;
      that.setData({
        goods: that.data.goods,
        miaosha_end_time_over: secondToTime(time_over, type),
      });
    }
    _init();
    timer = setInterval(function() {
      _init();
    }, 1000);
    function secondToTime(second, type) {
  
      let _h = parseInt(second / 3600, 10);
      let _m = parseInt((second % 3600) / 60, 10);
      let _s = second % 60;

      return {
        h: _h < 10 ? ('0' + _h) : (String(_h)),
        m: _m < 10 ? ('0' + _m) : (String(_m)),
        s: _s < 10 ? ('0' + _s) : (String(_s)),
        type: type,
      };
    }
  },
  to_dial() {
    let contact_tel = this.data.contact_tel;
    wx.makePhoneCall({
      phoneNumber: contact_tel,
    });
  },
  openService() {
    this.setData({
      show_service: true,
    });
  },
  closeService() {
    this.setData({
      show_service: false,
    });
  },
  downloadPicture() {
    utils.downLoad(this);
  },
  onNavigate(e) {
    let param = e.currentTarget.dataset;
    app.ws_micro_shop_navigate(param);
  },
  wxmlTagATap(e) {
    let src = e.detail.src || false;
    let reUrl = /^\//;
    if (!src) {
      return;
    } else {
      if (reUrl.test(src)) {
        app.util.navigateTo('/ws_micro_shop' + src);
      } else {
        app.util.navigateTo('/ws_micro_shop/pages/web/web?url=' + src);
      }
    }
  },
  collectFormId(e) {
    app.collectFormId(e);
  },
  tabMiniCard(e) {
    let args = e.detail;
    let currentPath = '';
    let pages = getCurrentPages();
    pages.length > 0 && (currentPath = '/' + pages.pop().route);
    (currentPath !== args.path
      || String(this.data.opts.id) !== args.query.id)
      && setTimeout(() => {
        app.util.navigateTo(args.path, args.query);
      }, 500);
  },
  favoriteAdd() {
    let _this = this;
    app.ws_micro_shoprequest({
      url: api.miaosha.favorite_add,
      data: {
        id: _this.data.id,
      },
      success: function (res) {
        if (res.code === 0) {
          let goods = _this.data.goods;
          goods.is_favorite = 1;
          _this.setData({
            goods,
          });
          wx.showToast({
            title: '收藏成功',
            icon: 'success',
            duration: 1500,
          });
        }
      },
    });
  },
  favoriteRemove() {
    let _this = this;
    app.ws_micro_shoprequest({
      url: api.miaosha.favorite_remove,
      data: {
        id: _this.data.id,
      },
      success: function (res) {
        if (res.code === 0) {
          let goods = _this.data.goods;
          goods.is_favorite = 0;
          _this.setData({
            goods,
          });
          wx.showToast({
            title: '已取消收藏',
            icon: 'success',
            duration: 1500,
          });
        }
      },
    });
  },
  getFloatIcon() {
    let that = this;
    let { dial, dial_pic, contact_tel, web_service, web_service_url, show_customer_service, serviceMessageTitle, serviceMessagePath, service, show_qywxcustomer_service, show_qywxcustomer_pic, card_openid, card_toopenid, card_id } = that.data;
    let floatItems = [
      {
        type: 1, // 客服电话
        show: dial == 1,
        icon: dial_pic,
        tel: contact_tel,
      },
      {
        type: 6, // 企业客服
        show: show_qywxcustomer_service == 1,
        icon: show_qywxcustomer_pic,
      },
      {
        type: 3, // webview跳转
        show: web_service,
        icon: web_service,
        url: web_service_url,
      },
      {
        type: 0, // 推荐
        show: false,
        iconClass: 'icon icon-xin',
        event: 'recommend',
      }
    ]
    
    let customerlist;
    if (Number(show_customer_service) === 1) {
      customerlist = [
        {
          type: 4, // 客服跳转
          show: true,
          icon: service,
          sessionFormStr: JSON.stringify({
            shop_id: app.ws_micro_shop_globalData.shopid,
          }),
          serviceMessageTitle: serviceMessageTitle,
          serviceMessagePath: serviceMessagePath,
        }
      ]
    } else if (Number(show_customer_service) === 2 || Number(show_customer_service) === 3) {
      customerlist = [
        {
          type: 7, //内部跳转
          show: true,
          icon: service,
          url: '/common/component/universal-card/pages/message?openid=' + card_openid + '&to_openid=' + card_toopenid + '&cardid=' + card_id + '&scene=inner&m_id=0'
        },
      ]
    }
    customerlist && (floatItems = floatItems.concat(customerlist));
    that.setData({
      floatItems
    },()=>{
      that.checkUserCardManage();
    });
  },

   // 判断当前模块是否开启了推荐
   checkRecommandBtn(){
    let { floatItems } = this.data;
    app.util.request({
      url:'card/record/getModuleRecommandButton',
      success: res => {
        let {errcode, data} = res.data;
        if(errcode == 0){
          floatItems.forEach(item =>{
            if(item.event == 'recommend'){
              item.show = data == 1? true: false;
            }
          })
          this.setData({
            floatItems
          })
        }
      }
    })
  },

  // 判断当前用户是否有名片及商品是否被加入到名片推荐商品中
  checkUserCardManage(){
    let { id } = this.options;
    let { floatItems } = this.data;
    app.util.request({
      url:'card/record/getUserCardManage',
      data:{
        id,
        type:'3',
        openid: wx.getStorageSync('openid') || wx.getStorageSync('OPENID')
      },
      success: res => {
        let {errcode, data:{is_cardmanage,is_havegoods}} = res.data;
        console.log("=====checkUserCardManage====",res.data);
        this.checkRecommandBtn();
        if(errcode == 0){
          floatItems.forEach(item =>{
            if(item.event == 'recommend'){
              item.show = is_cardmanage == 1? true: false;
              item.iconClass = is_havegoods == 1? 'icon icon-xinxin' :'icon icon-xin';
            }
          })
          this.setData({
            floatItems,
            is_havegoods
          })
        }
      }
    })
  },
  

  // 添加推荐商品
  recommend(){
    let { id } = this.options;
    let { floatItems, is_havegoods } = this.data;
    console.log("===is_havegoods====",is_havegoods)
    app.util.request({
      url:'card/record/addCardManageGoods',
      data:{
        id,
        type:'3',
        openid: wx.getStorageSync('openid') || wx.getStorageSync('OPENID'),
        options: is_havegoods == 0? '1': '2'
      },
      success: res => {
        console.log("===addCardManageGoods====",res.data.data)
        if(res.data.errcode == 0){
          is_havegoods = !is_havegoods;
          floatItems.forEach(item =>{
            if(item.event == 'recommend'){
              item.iconClass = is_havegoods == 1? 'icon icon-xinxin' :'icon icon-xin';
            }
          })
          let title = is_havegoods == 1?'推荐成功':'取消推荐成功';
          wx.showToast({
            title,
            icon:'none'
          })
        } else {
          wx.showToast({
            title:res.data.errmsg,
            icon:'none'
          })
        }
        this.setData({
          floatItems,
          is_havegoods
        })
      }
    })
  },
});
